package com.jt.config;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisSentinelPool;

@Configuration
//执行代码的主体jt-manage.
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
	
	@Value("${redis.cluster}")
	private String nodes;	
	/**
	 *配置redis集群
	 */
	@Bean
	public JedisCluster jedisCluster() {
		Set<HostAndPort> set = new HashSet<>();
		String[] nodeArray = nodes.split(",");
		for (String node : nodeArray) {
			String host=node.split(":")[0];
			int port=Integer.parseInt(node.split(":")[1]);
			set.add(new HostAndPort(host, port));
		}
		return new JedisCluster(set);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 核心思想:
	 * 	1.动态创建redis哨兵的池对象.
	 * 	2.动态的从池中获取jedis对象,实现数据的存取.
	 */
	
//	@Bean
//	public JedisSentinelPool jedisSentinelPool() {
//		
//		Set<String> sentinels = new HashSet<String>();
//		sentinels.add(sentinel);
//		return new JedisSentinelPool("mymaster", sentinels);
//	}
	//如果@bean注解中添加了参数,如果该参数spring容器中已经管理则可以动态的赋值.
//	@Bean
//	public Jedis jedis(JedisSentinelPool jedisSentinelPool) {
//		return jedisSentinelPool.getResource();
//	}

	
	
	
//	@Value("${redis.shards}")
//	private String nodes;
//	
//	//spring整合redis分片机制
//	@Bean
//	public ShardedJedis shardedJedis() {
//		String[] nodeArray = nodes.split(",");
//		List<JedisShardInfo> shards=new ArrayList<JedisShardInfo>();
//		for(String node : nodeArray) {
//			String host = node.split(":")[0];
//			int port = Integer.parseInt(node.split(":")[1]);
//			JedisShardInfo info = new JedisShardInfo(host,port);
//			shards.add(info);
//		}
//		return new ShardedJedis(shards);
//	}
	
	
	
	/*
	 * @Value("${redis.host}") private String node; //ip:port
	 * 
	 * //交给spring容器管理，手动封装redis对象.
	 * 
	 * @Bean public Jedis jedis() { String[] nodeArray = node.split(":"); String
	 * host = nodeArray[0]; int port = Integer.parseInt(nodeArray[1]); return new
	 * Jedis(host, port); }
	 */
}
